package cc.yaomm.common.basic.captcha.handler;

import cc.yaomm.common.basic.captcha.generator.CaptchaGenerator;
import cc.yaomm.common.basic.domain.KeyValue;
import cc.yaomm.common.basic.enums.CaptchaType;
import cc.yaomm.common.basic.exception.BusinessException;
import cc.yaomm.common.basic.captcha.config.CaptchaProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * Created by XQL on 2020/5/14.
 */
@Slf4j
public class EmailCaptchaHandler implements CaptchaHandler {

    public static final String REGEX = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    CaptchaProperties captchaProperties;

    @Autowired
    CaptchaGenerator captchaGenerator;

    @Autowired
    StringRedisTemplate redisTemplate;

//    @Autowired
//    JavaMailSenderImpl javaMailSender;

    @Override
    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    @Override
    public String generate(CaptchaType captchaType, String payload, Object... params) {
        if (!payload.matches(REGEX)) {
            throw new BusinessException("邮件账号不正确");
        }

        KeyValue<String, String> captcha = captchaGenerator.generate();

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(payload);
        message.setSubject(captchaProperties.getMail().getTitle());
        message.setText(captchaProperties.getMail().getContent()
                .replace("{code}", captcha.getKey()));

//        javaMailSender.send(message);

        //缓存验证 设置有效期
        this.setCache(captchaType, payload, captcha.getValue(), captchaProperties.getExpire());

        return Boolean.TRUE.toString();
    }
}
